import 'package:get/get.dart';
import 'package:sqflite/sqflite.dart';

import '../entity/meeting_data.dart';

/// 数据库
mixin DbMixin on GetxService {
  late Database database;

  @override
  void onInit() async {
    super.onInit();
    database = await openDatabase('my_meeting.db', version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute('''
          CREATE TABLE meetings(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            createTime TEXT,
            meetingName TEXT,
            meetingContent TEXT,
            meetingState INTEGER,
            meetingBeginTime TEXT,
            meetingEndTime TEXT,
            meetingAddress TEXT,
            participants TEXT,
            meetingMinutes TEXT,
            deviceOpen TEXT,
            facilities TEXT
          )
        ''');
    });
  }

  /// 插入
  Future<void> insertMeeting(MeetingData meeting) async {
    final db = await database;
    await db.insert('meetings', meeting.toMap());
  }

  /// 获取所有会议
  Future<List<MeetingData>> getMeetings() async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query('meetings');
    return List.generate(maps.length, (i) {
      return MeetingData.fromMap(maps[i]);
    });
  }

  /// 更新会议
  Future<void> updateMeeting(MeetingData meeting) async {
    final db = await database;
    await db.update(
      'meetings',
      meeting.toMap(),
      where: 'id = ?',
      whereArgs: [meeting.id],
    );
  }

  /// 删除会议
  Future<void> deleteMeeting(int id) async {
    final db = await database;
    await db.delete(
      'meetings',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  Future<void> onClose() async {
    super.onClose();
    await database.close();
  }
}
